package com.dexilaonian.photo.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.R;
import com.dexilaonian.activity.OnlineVolunteerActivity;
import com.dexilaonian.permission.AfterPermissionGranted;
import com.dexilaonian.permission.PermissionUtils;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.BitmapZip;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.FileUtils;
import com.dexilaonian.utils.ImageLoader;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.view.MultiImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class VolunteerActivity extends BaseActivity {

    private static final int CAMERA_PERIMISSION_CODE = 2;
    private static final int REQUEST_IMAGE = 3;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service3)
    TextView baseTitleService3;
    @Bind(R.id.tv_volunteer_person)
    TextView tvVolunteerPerson;
    @Bind(R.id.etText_volunteer)
    EditText etTextVolunteer;
    @Bind(R.id.tv_volunteer_num)
    TextView tvVolunteerNum;
    @Bind(R.id.volunteerPic1)
    ImageView volunteerPic1;
    @Bind(R.id.takepic)
    TextView takepic;
    @Bind(R.id.takepic_detail)
    TextView takepicDetail;
    @Bind(R.id.rl_volunteerPic)
    RelativeLayout rlVolunteerPic;
    @Bind(R.id.btn_volunteer22)
    Button btnVolunteer22;

    private String imageUrl = "";

    @Override
    public int getLayoutID() {
        return R.layout.activity_volunteer;
    }

    @Override
    public void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        // initListener();
    }


    private ArrayList<String> mSelectPath = new ArrayList<>();

    @AfterPermissionGranted(CAMERA_PERIMISSION_CODE)
    public void startPickPicActivity() {
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        //selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
        boolean showCamera = true;
        int maxNum = 3;
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    postFile(new File(mSelectPath.get(i)));
                }
            }
        }
    }

    /**
     * 上传文件
     */
    private void postFile(File file) {
        final String pic_path = file.getPath();
        String targetPath = FileUtils.getSDCardPath() + file.getName();
        //压缩图片的方法
        final String compressImage = BitmapZip.compressImage(pic_path, targetPath, 90);
        final File compressedPic = new File(compressImage);
        if (compressedPic.exists()) {
            file = compressedPic;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        showProgressBar(true);
        String url = Constant.base_url + "/upload/image";
        Okhttp.postFileParams(url, file, params, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(e.getMessage());
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showToast(response);
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String content = jsonObject.optString("data");
                    JSONObject content_json = new JSONObject(content);
                    String face = content_json.optString("path");
                    if (!TextUtils.isEmpty(face)) {
                        volunteerPic1.setVisibility(View.VISIBLE);
                        takepic.setVisibility(View.GONE);
                        imageUrl = Constant.base_pic_url + face;
                        ImageLoader.displayCircle(VolunteerActivity.this, imageUrl, volunteerPic1);
                        new DownloadImageTask().execute(imageUrl);
                        PreferencesUtil.putString(VolunteerActivity.this, Constant.IMAGE, imageUrl);
                        showToast("头像上传成功");
                    } else {
                        showToast("头像上传失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });
    }

    private void initBtnVol() {
        String volunteer_url = Constant.base_url + "/topic/save.do";
        Map<String, String> volunteer_map = new HashMap<>();
        String volunteer = etTextVolunteer.getText().toString().trim();
        if (TextUtils.isEmpty(volunteer)) {
            showToast("请输入问题，谢谢");
            return;
        }
        volunteer_map.put("content", volunteer);
        volunteer_map.put("imageUrl", imageUrl);
        Okhttp.postString(true, volunteer_url, volunteer_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(state);
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                Log.e("TTTTimage", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String data = jsonObject.optString("data");
                    JSONObject js = new JSONObject(data);
                    String topicId = js.optString("topicID");
                    String imageUrl = js.optString("imageUrl");
                    String avatar = js.optString("avatar");
                    String content = js.optString("content");
                    Intent intent = new Intent(VolunteerActivity.this, OnlineVolunteerActivity.class);
                    intent.putExtra("topicId", topicId);
                    intent.putExtra("imageUrl", imageUrl);
                    intent.putExtra("avatar", avatar);
                    intent.putExtra("content", content);
                    startActivity(intent);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
                showProgressBar(false);
            }
        });
    }

    @OnClick({R.id.back, R.id.rl_volunteerPic,R.id.btn_volunteer22})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rl_volunteerPic:
                String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                if (PermissionUtils.hasPermissions(VolunteerActivity.this, perms)) {
                    startPickPicActivity();
                } else {
                    PermissionUtils.requestPermissions(VolunteerActivity.this, "需要拍照和相册权限", CAMERA_PERIMISSION_CODE, perms);
                }
                break;
            case R.id.btn_volunteer22:
                initBtnVol();
                break;
        }
    }

private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

    protected Drawable doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    protected void onPostExecute(Drawable result) {
        volunteerPic1.setBackgroundDrawable(result);
    }

}

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过第二个参数(文件名)来判断，是否本地有此图片
            drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
        } catch (IOException e) {
            Log.e("TTTskythinking", e.getMessage());
        }

        return drawable;
    }

    private void initListener() {
        etTextVolunteer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (etTextVolunteer.length() != 0) {
                    tvVolunteerNum.setText(etTextVolunteer.length() + "/500");
                    Log.e("TTTS", s + "====count" + count);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }
}

